/**************************************************************************************************
  Filename:       misc_func.c
  Revised:        $Date: 2014-12-08 10:20:18 +0800 (Fri, 04 Apr 2014) $
  Revision:       $Revision: 10001 $

  Description:    This file contains miscellaneous functions.
**************************************************************************************************/

#include "misc_func.h"

static void adcBattMeasSetupCB( void );
static void adcBattMeasTeardownCB( void );
static void softCmdBattCB(uint8 event);


void GAP_Setup(void)
{
	  // Setup the GAP
  VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );
  
  // Setup the GAP Peripheral Role Profile
  {
    // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed
    uint8 initial_advertising_enable = TRUE;
    
    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16 gapRole_AdvertOffTime = 1000;
  
    uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;
    
    GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN,90000);
    // Set the GAP Role Parameters
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
    GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );
  
    GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( deviceName ), deviceName );
    GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );
  
    GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
    GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
    GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
    GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
    GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
  }
  
  // Set the GAP Attributes
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );

  // Setup the GAP Bond Manager
  {
    // here need a if
    uint32 passkey = MAXTAIN_PASSCODE;
    // uint32 passkey = 0;
    uint8 pairMode = GAPBOND_PAIRING_MODE_INITIATE;//GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;         //GAPBOND_PAIRING_MODE_INITIATE
    uint8 mitm = TRUE;
    uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
    uint8 bonding = TRUE;
    
    GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof( uint32 ), &passkey );
    GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode );
    GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm );
    GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap );
    GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding );
  }
  

  // Initialize GATT attributes
  GGS_AddService( GATT_ALL_SERVICES );         // GAP
  GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes
  
  Data_AddService( GATT_ALL_SERVICES ); 
  
  DevInfo_AddService();   // Device Information Service
  Batt_AddService( );     // Battery Service
  Batt_Register( softCmdBattCB );
  //  Accel_AddService( GATT_ALL_SERVICES );      // Accelerometer Profile
  Batt_Setup( HAL_ADC_CHN_AIN7, BATT_ADC_LEVEL_2V, BATT_ADC_LEVEL_3V, adcBattMeasSetupCB, adcBattMeasTeardownCB, NULL );
  //Humi_AddService( GATT_ALL_SERVICES ); 

}

static void softCmdBattCB(uint8 event)
{
  if (event == BATT_LEVEL_NOTI_ENABLED)
  {
    // if connected start periodic measurement
    // if (softCmdGapState == GAPROLE_CONNECTED)
    {
      dbg("BATT_LEVEL_NOTI_ENABLED\n");
      // osal_start_timerEx( softCmdTaskId, BATT_PERIODIC_EVT, DEFAULT_BATT_PERIOD );
    } 
  }
  else if (event == BATT_LEVEL_NOTI_DISABLED)
  {
    dbg("BATT_LEVEL_NOTI_DISABLED\n");
    // stop periodic measurement
    // osal_stop_timerEx( softCmdTaskId, BATT_PERIODIC_EVT );
  }
}
void enMPUInterrupt(void)
{
  /******
  *  Interrupt set P0.5 as input interrupt  (1<<6)
  * Only P0.5
  ******/
  // P0SEL &= ~0x20;                  //GPIO
  // P0DIR &= ~0x20;                  //INPUT
  // PICTL |= 0x00;                   //Rising edge on input gives interrupt.
  // IEN1  |= 0x20;                   //P0IE  enable P0 interrupt enable          
  // P1IEN |= 0x20;                   //Port0.5         0000 0100
  /**  End of Interrupt init**/
  // P0.5 && P0.6
  P0SEL &= ~0x60;                  //GPIO
  P0DIR &= ~0x60;                  //INPUT
  PICTL |= 0x00;                   //Rising edge on input gives interrupt.
  IEN1  |= 0x60;                   //P0IE  enable P0 interrupt enable          
  P1IEN |= 0x60;                   //Port0.5         0000 0100
}

void batteryMonitorInit(void)
{
  /*******
  * Battery init ADC
  *******/
   {// Setup Battery Characteristic Values
     uint8 critical = DEFAULT_BATT_CRITICAL_LEVEL;

     Batt_SetParameter( BATT_PARAM_CRITICAL_LEVEL, sizeof (uint8), &critical );
     Batt_Setup( HAL_ADC_CHN_AIN7, BATT_ADC_LEVEL_2V, BATT_ADC_LEVEL_3V, adcBattMeasSetupCB, adcBattMeasTeardownCB, NULL );

     // P0DIR |= (1<<1);  //Control of transistor in the battery measurement voltage divider 
     // P0SEL &= ~(1<<1);
     // P0_0 = 0; // Stop feeding current through voltage divider
    
     // P0DIR |= (1<<8);/* Analog measuring pin setup. This will be retained during ADC read */
     // P0SEL &= ~(1<<8);
     // P0_1 = 0; // LOW output to stop leakage current due to default pull-up
  }
  /******  Batt Monitor Init *******/
}


/*********************************************************************
 * @fn      adcBattMeasSetupCB
 *
 * @brief   Callback from battery service to set up measurement environment
 *
 * @param   none
 *
 * @return  none
 */
static void adcBattMeasSetupCB( void )
{
  //P0_0 = 1;  // Open transistor in voltage divider
  
  /* Analog pin P0.1 is configured by HAL ADC routine */
}

/*********************************************************************
 * @fn      hidAdvRemoteBattMeasTeardownCB
 *
 * @brief   Callback from battery service to tear down measurement environment
 *
 * @param   none
 *
 * @return  none
 */
static void adcBattMeasTeardownCB( void )
{
  //P0_0 = 0; // Stop feeding current through voltage divider
  
  /* Idle state P0.1 settings are retained from Init */
}

//Test
//static void ValueToString(uint16 Data ,uint8 *Buff);
//static void resetCharacteristicValue(uint16 servUuid, uint8 paramID, uint8 value, uint8 paramLen);
// static void performTest()
// {
//     //  HAL_ADC_RESOLUTION_14   8191
//     //  HAL_ADC_RESOLUTION_12   2047
// #if defined( HAL_ADC_TEST )
//     HalAdcSetReference(HAL_ADC_REF_AVDD);
//     uint16 adc_vol=HalAdcRead(HAL_ADC_CHN_AIN0,HAL_ADC_RESOLUTION_14);
//     uint16 vol = (uint16)(2.8 * adc_vol / 8191 * 100);
//     uint8 vols[8];
//     ValueToString(vol,vols);
//     #if defined( DEBUG )
//         HalUARTWrite(0,vols,8);
//     #endif
// #endif
// #if defined( HAL_TEMP_TEST )
//     //According to CC2541 Page 10 Analog Temperature Sensor    
//     TR0 = 0x01;
//     ATEST = 0x01;
//     HalAdcSetReference(HAL_ADC_REF_125V);
//     uint16 adc_temp=HalAdcRead(HAL_ADC_CHN_TEMP,HAL_ADC_RESOLUTION_12);
//     // actual temperature = (ADC_TEMP - (1480 - 4.5*25))/4.5 = (ADC_TEMP - 1367.5)/4.5
//     uint16 tmp = (uint16)(100*(adc_temp - 1367.5)/4.5);                         //(uint16)(1.24 * adc_temp / 8191 * 100);
//     uint8 temp[8];
//     ValueToString(tmp,temp);

//     #if defined( DEBUG )
//         HalUARTWrite(0,temp,8);
//     #endif

// #endif
    
// #if defined( HAL_I2C_TEST )
//     uint8 charValue5[5] = { 0,0,0,0,0 };
//    // AccInit();
//     charValue5[0]=AccGetXAxis();
//     charValue5[1]=AccGetYAxis();
//     charValue5[2]=AccGetZAxis();
//     charValue5[3]=AccGetTilt();
//     charValue5[4]=AccGetOPSTAT();
//     //AccStop();
// #if !defined( DEBUG )    
//     HalUARTWrite(0,charValue5,5);
// #endif
// #endif
    
    
// }

// static void ValueToString(uint16 Data ,uint8 *Buff)
// {
//   Buff[0] = (Data/10000)+0x30; 
//   Buff[1] = ((Data/1000)%10)+0x30; 
//   Buff[2] = ((Data/100)%10)+0x30; 
//   Buff[3] = '.'; 
//   Buff[4] = ((Data/10)%10)+0x30; 
//   Buff[5] = (Data%10)+0x30; 
//   Buff[6] = '\n'; 
//   Buff[7] = '\0';
//}
